package ListNode1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-08
 * Time:22:25
 */
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

public class ReverseLinkedList {
    // 反转链表的核心方法
    public static ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode prev = null;
        ListNode curr = head;
        while (curr!= null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    // 用于创建简单链表的辅助方法，方便测试
    public static ListNode createLinkedList(int[] values) {
        if (values == null || values.length == 0) {
            return null;
        }
        ListNode head = new ListNode(values[0]);
        ListNode current = head;
        for (int i = 1; i < values.length; i++) {
            current.next = new ListNode(values[i]);
            current = current.next;
        }
        return head;
    }

    // 打印链表的辅助方法
    public static void printLinkedList(ListNode head) {
        while (head!= null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        // 创建一个简单的链表: 1 -> 2 -> 3 -> 4 -> 5
        int[] values = {1, 2, 3, 4, 5};
        ListNode head = createLinkedList(values);

        System.out.println("原链表:");
        printLinkedList(head);

        ListNode reversedHead = reverseList(head);

        System.out.println("反转后的链表:");
        printLinkedList(reversedHead);
    }
}
